package com.css.zfzx.sjcj.modules.qhpolygonresultmap.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.DivisionRepository;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.qhpolygonresultmap.repository.PolygonResultMapNativeRepository;
import com.css.zfzx.sjcj.modules.qhpolygonresultmap.repository.entity.PolygonResultMapEntity;
import com.css.zfzx.sjcj.modules.qhpolygonresultmap.viewobjects.PolygonResultMapQueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.List;

/**
 * @author zyb
 * @date 2020-12-19
 */
@Repository
@PropertySource("classpath:platform-config.yml")
public class PolygonResultMapNativeRepositoryImpl implements PolygonResultMapNativeRepository {
    @PersistenceContext
    private EntityManager em;

    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.areaCode}")
    private String areaCode;
    @Autowired
    private DivisionRepository divisionRepository;
    private static final Logger log = LoggerFactory.getLogger(PolygonResultMapNativeRepositoryImpl.class);


    @Override
    public Page<PolygonResultMapEntity> queryHddcDResultmaptables(PolygonResultMapQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        StringBuilder sql = new StringBuilder("select * from qh_polygon_result_map ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city = :city");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and area = :area");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCityname())) {
            whereSql.append(" and cityname like :cityname");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getFilename())) {
            whereSql.append(" and filename like :filename");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getId())) {
            whereSql.append(" and id like :id");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getAuthors())) {
            whereSql.append(" and authors like :authors");
        }
        /*if (!PlatformObjectUtils.isEmpty(queryParams.getPageType())) {
            whereSql.append(" and extends20 = :pagetype");
        }*/
        whereSql.append(" and is_valid=1");
        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        //是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        //是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        //是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        //是否为县级管理员
        boolean containtRoleArea= ServerUtil.isContaintRole(roles, areaCode);
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user =:userId");
            }
            if(containtRolePro){
                whereSql.append(" and province like :authProvince");
            }
            if(containtRoleCity){
                whereSql.append(" and city like :authCity");
            }
            if(containtRoleArea){
                whereSql.append(" and area like :authArea");
            }
        }
        whereSql.append(" and is_valid=1");
        if (!PlatformObjectUtils.isEmpty(sort)) {
            whereSql.append(" order by "+sort+" "+order);
        }
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), PolygonResultMapEntity.class);
        StringBuilder countSql = new StringBuilder("select count(*) from qh_polygon_result_map ");
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());
        if (!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", queryParams.getProvince());
            countQuery.setParameter("province", queryParams.getProvince());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", queryParams.getCity());
            countQuery.setParameter("city", queryParams.getCity());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("area", queryParams.getArea());
            countQuery.setParameter("area", queryParams.getArea());
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getCityname())) {
            query.setParameter("cityname", "%" + queryParams.getCityname() + "%");
            countQuery.setParameter("cityname", "%" + queryParams.getCityname() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getFilename())) {
            query.setParameter("filename", "%" + queryParams.getFilename() + "%");
            countQuery.setParameter("filename", "%" + queryParams.getFilename() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getId())) {
            query.setParameter("id", "%" + queryParams.getId() + "%");
            countQuery.setParameter("id", "%" + queryParams.getId() + "%");
        }
        if (!PlatformObjectUtils.isEmpty(queryParams.getAuthors())) {
            query.setParameter("authors", "%" + queryParams.getAuthors() + "%");
            countQuery.setParameter("authors", "%" + queryParams.getAuthors() + "%");
        }
        /*if (!PlatformObjectUtils.isEmpty(queryParams.getPageType())) {
            query.setParameter("pagetype",  queryParams.getPageType());
            countQuery.setParameter("pagetype", queryParams.getPageType());
        }else{
            query.setParameter("pagetype",  "3");
            countQuery.setParameter("pagetype", "3");
        }*/
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                query.setParameter("userId",PlatformSessionUtils.getUserId());
                countQuery.setParameter("userId", PlatformSessionUtils.getUserId());
            }
            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = validDivisionById.getDivisionName();
            if(containtRolePro){
                query.setParameter("authProvince","%"+divisionName+"%");
                countQuery.setParameter("authProvince","%"+divisionName+"%");
            }
            if(containtRoleCity){
                query.setParameter("authCity","%"+divisionName+"%");
                countQuery.setParameter("authCity","%"+divisionName+"%");
            }
            if(containtRoleArea){
                query.setParameter("authArea","%"+divisionName+"%");
                countQuery.setParameter("authArea","%"+divisionName+"%");
            }
        }

        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<PolygonResultMapEntity> list = query.getResultList();
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        Page<PolygonResultMapEntity> hddcDResultmaptablePage = new PageImpl<>(list, pageable, count.longValue());
        return hddcDResultmaptablePage;
    }
}
